﻿using SiliconSelect.BLL;
using SiliconSelect.Common;
using SiliconSelect.PlcComunication;
using SiliconSelect.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SiliconSelect.Views.UserOperatorDialog
{
    /// <summary>
    /// CalibrationProgressBar.xaml 的交互逻辑
    /// </summary>
    public partial class CalibrationProgressBar : Window
    {
        CalibrationViewModel viewModel = new CalibrationViewModel();
        SocketServer server3D;
        Action CalibraionTask; // 标定任务
        public CalibrationProgressBar(SocketServer server, Action cal3DTask)
        {
            InitializeComponent();
            server3D = server;
            CalibraionTask = cal3DTask;
            DataContext = viewModel;
            Task.Run(() =>
            {
                RunRefreshTask();
            });
        }

        private async void RunRefreshTask()
        {
            int loopCount = 0;
            int loopCountMax = 50;
            CalibraionTask?.Invoke(); // 调用标定任务.
            while (!server3D.Calibration3DIsOK && !viewModel.CloseRefresh)
            {
                if (++loopCount >= loopCountMax)
                {
                    break;
                }
                Dispatcher.Invoke(new Action(() =>
                {
                    if (loopCount <= 10)
                    {
                        viewModel.Value = loopCount * (9);
                    }
                    else
                    {
                        viewModel.Value = 90 + (loopCount / 4);
                        if (viewModel.Value > 100)
                        {
                            viewModel.Value = 100;
                        }
                    }
                }));
                await Task.Delay(50);
            }
            viewModel.Value = 0;
            viewModel.CloseRefresh = true;
            Dispatcher.Invoke(new Action(() =>
            {
                Close();
            }));
        }
    }
}